import $ from 'jquery';
import md5 from 'blueimp-md5';
import in_array from 'in_array';
import tool from '../tool';


// var mys = require('store')
// var expirePlugin = require('store/plugins/expire')
// mys.addPlugin(expirePlugin)

import store from './store'
import http from './http'
import auth from './auth'
import ui from './ui'
import data from './data'
import _ from 'lodash'

export default {
    data,
    store,
    http,
    auth,
    ui,
    mydelay(clb, time = 100) {
        setTimeout(() => {
            clb();
        }, time);
    },
    mywait(_this, flag, clb, time = 0, delay = 100, stop = 10) {
        if (_this[flag])
            clb();
        else
            setTimeout(() => {
                // tool.cl('time:', time);
                // tool.cl('_this[flag]:', _this[flag]);
                time = time + 1;
                if (time > stop)
                    return;
                if (_this[flag]) {
                    clb();
                } else {
                    this.mywait(_this, flag, clb, time, delay);
                }
            }, delay);
    },
    myutil(_this, util_clb, clb, time = 0, delay = 100, stop = 10) {
        setTimeout(() => {
            // tool.cl('time:', time);
            time = time + 1;
            if (time > stop)
                return;
            if (util_clb()) {
                clb();
            } else {
                this.myutil(_this, util_clb, clb, time, delay);
            }
        }, delay);
    },
    is_admin(_this) {
        let md5ed = _this.$cookie.get('txy_tz_admin_id');


        let admins = _this.$cookie.get('txy_adminlist');

        admins = admins.split(",");

        admins = admins.map(item => {
            return md5(item);
        });

        return in_array(md5ed, admins);
    },
    set(_this, obj, attr, val) {

        _this.$set(_this[obj], attr, val);
    },
    setCtlinfo(_this) {
        this.store.commit(_this, 'setCctl', _this.$route.query.ctl);
        this.store.commit(_this, 'upTopMid');
        this.store.commit(_this, 'setCurrentTopMenu');

    },
    jump(_this, path) {
        let f = 0;
        if (path === 1) {
            f = 1;
            let _path = _this.$route.path
            let arr = ['/page/add', '/page/edit', '/page/menu_group']
            path = arr.contains(_path) ? '/page/list' : '/page/add'
        }
        _this.$router.push({
            path: path,
            query: f === 1 ? _this.$route.query : {}
        })
    },
    getDataCom: http.getDataCom,
    eventEmit(_this, event, ...param) {
        // eventEmit(_this, event, param) {
        let eventVue = this.store.get(_this, 'eventVue');
        eventVue.$emit(event, ...param);
    },
    eventOn(_this, event, fun) {
        let eventVue = this.store.get(_this, 'eventVue');
        eventVue.$on(event, fun);
    },
    showDiyConfirm(_this, clb, html) {
        let option = {
            name: 'confirm',
            data: {
                fn: {
                    sure: clb
                },
                html
            }
        };
        this.eventEmit(_this, 'showPopCom', option);
    },
    showConfirm(_this, clb, option = null) {
        let eventVue = this.store.get(_this, 'eventVue');
        let popOption = {
            header: '提示',
            msgTypeIcon: 'warning',
            msgType: 'warning',
            delay: 50,
            content: '确认此操作吗？',
            positive: '确定',
            negative: '取消',
            yes_event: clb
        };
        if (option)
            _.merge(popOption, option);
        eventVue.$emit('setPop', popOption);
    },
    showDimmer(_this) {
        this.eventEmit(_this, 'showDimmer');
    },
    showMsg(_this, type, msg, jump = null, clb = null) {
        let conf = {
            auto_hide: true
        };
        if (this.isObject(type)) {
            conf = _.merge(conf, type);
            type = conf.type;
        }

        msg = msg || null
        let eventVue = this.store.get(_this, 'eventVue');
        let option = this.getMsgOption(type, msg);
        option.no_action = true
        if (clb)
            option.hide_event = clb

        eventVue.$emit('setPop', option)

        let time = 1000;
        switch (type) {
            case 'short_error':
                time = 2000;
                break;
            case 'error':
                time = 2500;
                break;
            case 'info':
                time = 1500;
                break;
        }
        time = conf.time || time;

        if (conf.auto_hide) {
            setTimeout(() => {
                eventVue.$emit('hidePop')
                if (jump) {
                    if (this.isNumber(jump))
                        _this.$router.go(jump)
                    else
                        _this.$router.push(jump)
                }
            }, time)
        }


        eventVue.$emit('setSaveLoading', false)
        _this.loadingBtn = false
    },
    getMsgOption(type, msg){
        let msgs = {
            success: {
                header: '消息',
                msgTypeIcon: 'smile',
                msgType: 'success',
                content: msg || '恭喜你，操作成功！',
            },
            quick_error: {
                header: '错误',
                msgTypeIcon: 'frown',
                msgType: 'error',
                content: msg || '抱歉，操作失败！',
            },
            error: {
                header: '错误',
                msgTypeIcon: 'frown',
                msgType: 'error',
                content: msg || '抱歉，操作失败！',
            },
            info: {
                header: '消息',
                msgTypeIcon: 'info',
                msgType: 'info',
                content: msg,
            },
            warning: {
                header: '警告',
                msgTypeIcon: 'warning',
                msgType: 'warning',
                content: msg || '抱歉，操作失败！',
            },

        }
        let option = msgs[type];
        return option;
    },
    showNoHide(_this, msg, type = 'info'){
        let conf = {
            auto_hide: false,
            type
        };
        this.showMsg(_this, conf, msg);
    },
    showEditPop(_this, info) {
        let eventVue = this.store.get(_this, 'eventVue');
        eventVue.$emit('setModal');
        eventVue.$emit('setModalContent', info);
    },
    showMypop(_this, type, msg, _option = null){
        let option = this.getMsgOption(type, msg);

        if (_option) {
            option = _.merge(option, _option);
        }
        let eventVue = this.store.get(_this, 'eventVue');
        eventVue.$emit('showMypop', option);
    },
    showPopCom(_this, _option = null){
        let option = {_this: this};
        if (_option) {
            option = _.merge(option, _option);
        }
        this.eventEmit(_this, 'showPopCom', option);
    },
    showMybind(_this, _option = null, clb = null){
        let option = {
            clb
        };
        if (_option) {
            option = _.merge(option, _option);
        }
        let eventVue = this.store.get(_this, 'eventVue');
        eventVue.$emit('showPopBind', option);
    },
    getOp(_this){
        let isinEditModal = this.store.get(_this, 'isinEditModal', 'edit');
        let isinOtherEdit = store.get(_this, 'isinOtherEdit', 'edit');

        let op_type = isinEditModal ? 'modal_op' : (isinOtherEdit ? 'otherEdit_op' : 'op');
        let op = this.store.get(_this, op_type);
        return op;
    },
    getRandom(Max, Min) {
        Min = Min || 0
        var Range = Max - Min;
        var Rand = Math.random();
        return (Min + Math.round(Rand * Range));
    },
    getHardCode(_this, name, clb) {
        let url = tool.getApi(null, 'Get', 'getHardCode');
        let param = {};
        param.name = name;


        this.getDataCom(_this, url, param, (data) => {
            let nrs = null;
            if (this.isArray(name)) {
                nrs = [];
                name.forEach((item, ind) => {
                    nrs.push(this.hlHardCode(data[ind]))
                });
            } else
                nrs = this.hlHardCode(data)
            clb(nrs);
        });

    },
    modelFn(ctl, fn, ...param){
        let model = require('../model/index');
        let rs = null;
        if (model['default'][ctl] && model['default'][ctl][fn])
            rs = model['default'][ctl][fn](...param);
        return rs;
    },
    hlField(fields) {
        let tmp = {}
        fields.forEach(field => {

            tmp[field.id] = field

        })
        return tmp
    },
    hlHardCode(data) {
        let nd = []
        this.forEach(data, (key, item) => {
            let tmp = {}
            tmp.id = key
            tmp.title = item
            nd.push(tmp)
        });
        return nd;
    },
    getBindField(_this, mid, is_zip, clb) {
        is_zip = is_zip || 0
        if (mid) {
            let url = tool.getApi(null, 'Editget', 'getFields');

            let param = {
                mid: mid,
                is_zip: is_zip
            }
            this.getDataCom(_this, url, param, (data) => {
                clb(data);
            });
        }
    },
    getApiData(url, data) {

        let rs = '';
        // tool.cl(data)
        $.ajax({
            type: "POST",
            url: url,
            data: data,
            async: false,
            dataType: "json",
            success: function (result) {
                rs = result.data;
            },
            failure: function (result) {
                rs = false;
            }
        });
        return rs;
    },
    // mys: mys,
    forEach(obj, clb, selector = null) {

        if (obj instanceof Array) {
            obj.forEach((item, ind) => {
                if (selector)
                    clb.call(selector, ind, item)
                else
                    clb(ind, item)
            })
        } else {
            for (let key in obj) {
                if (obj.hasOwnProperty(key)) {
                    if (selector)
                        clb.call(selector, key, obj[key])
                    else
                        clb(key, obj[key])
                }

            }
        }

    },
    setC(key, val, exp) {
        exp = exp || 30;
        var expiration = new Date().getTime() + exp * 1000;
        // tool.cl(new Date().getTime())
        // tool.cl(expiration)
        mys.set(key, val, expiration)
    },
    getC(key) {
        return mys.get(key);
    },
    deepCopy(p, c) {
        var c = c || {};
        //  tool.cl(p)
        for (var i in p) {
            // tool.cl(i+':',p[i])
            if (typeof p[i] === 'object' && p[i] !== null) {
                c[i] = (p[i].constructor === Array) ? [] : {};
                this.deepCopy(p[i], c[i]);
            } else {
                c[i] = p[i];
            }
        }
        return c;
    },
    isArray(obj) {
        return (typeof obj == 'object') && obj.constructor == Array;
    },
    isString(str) {
        return (typeof str == 'string') && str.constructor == String;
    },
    isNumber(obj) {
        return (typeof obj == 'number') && obj.constructor == Number;
    },
    isDate(obj) {
        return (typeof obj == 'object') && obj.constructor == Date;
    },
    isFunction(obj) {
        return (typeof obj == 'function') && obj.constructor == Function;
    },
    isObject(obj) {
        return (typeof obj == 'object') && obj.constructor == Object;
    },
    getObjArrAttr(arr, attr) { //获得对象数组中每个对象的一个属性组成的数组
        let tmp = []
        arr.forEach(item => {
            tmp.push(item[attr])
        })
        return tmp;
    },
    id2Key(arr, field) { //把对象数组中每个对象的一个字段作为新数组的key
        field = field || 'id';
        let tmp = [];
        arr && arr.forEach(item => {
            tmp[item[field]] = item
        });
        return tmp;
    },
    proEnumVal(start, end){
        let tmp = []
        for (let i = start; i <= end; i++) {
            tmp.push({
                id: i,
                title: i
            })
        }
        return tmp;
    }

}
